﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 连锁激光
/// </summary>
public class InterlockLaser : Laser {

	public Collider2D[] colliderArr;//储存所有物体的collider
	public Transform tempEnemy;
	public GameObject laser;
	private WeaponInfo weaponInfo;
	private bool isFind;
	private GameObject gameObj;
	void Start () {
		isFind = false;
		colliderArr = null;
		gun = transform.parent.gameObject;
		lineRenderer = gameObject.GetComponent<LineRenderer>();
		lineRenderer.enabled = false;
		weaponInfo = gun.GetComponent<HeroGun> ().GetWeaponInfo();
	}
		

	// 寻找并设置攻击目标
	// if(weaponId == 0)return;
	private void FindTarget(){
		if (target != null) 
		{
			isFind = true;
			// 得到碰撞器
			colliderArr = Physics2D.OverlapCircleAll(target.transform.position,10, 1 << LayerMask.NameToLayer("EnemyPlane")|1<<LayerMask.NameToLayer("Enemy"));
			Debug.Log (colliderArr.Length);
			if (colliderArr.Length > 1) 
			{
				tempEnemy = colliderArr [Random.Range(0,colliderArr.Length)].transform;
				gameObj = GameObject.Instantiate(laser);
				gameObj.transform.position = new Vector3(target.transform.position.x, target.transform.position.y, 0);
				gameObj.transform.rotation = target.transform.rotation;
				gameObj.GetComponent<Laser>().SetTarget(tempEnemy.gameObject);
				gameObj.GetComponent<Laser>().SetWeaponInfo(weaponInfo);
				gameObj.GetComponent<Laser>().trigger = trigger;
				gameObj.GetComponent<Laser>().isAttack = true;
				gameObj.GetComponent<Laser>().isInPool = false;
				gameObj.GetComponent<Laser> ().isInterlock = true;
				gameObj.GetComponent<Laser> ().durationTime = 5 - timer;
				gameObj.transform.SetParent(this.transform.parent);
			}
		}
	}

	void Update()
	{
		Attacking ();
		if (isFind == false) 
		{
			FindTarget ();
		} else {
			if (gameObj != null) {
				interlockPos = endPosition;
				gameObj.GetComponent<Laser> ().interlockPos = interlockPos;
				if (target == null) 
				{
					Destroy (gameObj);
					gameObj = null;
				}
			}
		}
	}
}
